﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.Mvvm.Messaging.Messages;
using Microsoft.Win32;
using NPOI.SS.UserModel;
using SharpSvn;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows.Shapes;
using VteamProjectAssistant.Constants;
using VteamProjectAssistant.SettingWindow;

namespace VteamProjectAssistant
{
    public partial class MainWindowViewModel : ObservableObject, IDisposable
    {

        private readonly IMessenger _messenger;

        [ObservableProperty]
        private string? _editMode;

        [ObservableProperty]
        private string? _svnUserName;

        [ObservableProperty]
        private string? _excelFilePath;

        [ObservableProperty]
        private bool? _hasVersionControl;

        public MainWindowViewModel(IMessenger messenger)
        {
            _messenger = messenger;
            OnRegistryMessageReceiver();
        }

        // 重写OnActivated方法，在此注册消息
        private void OnRegistryMessageReceiver()
        {
            // 使用 Messenger 属性（来自基类）进行注册
            _messenger.Register<MainWindowViewModel, ValueChangedMessage<string>, string>(
                this,
                MessageEventTokenConstant.UPDATE_SVN_USER_NAME,
                (recipient, message) =>
                {
                    SvnUserName = message.Value;
                });
        }

        /// <summary>
        /// 加载SVN用户名
        /// </summary>
        [RelayCommand]
        private void LoadSvnUserName()
        {
            string userHome = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            string configFileName = "project_assistant_config.json";
            // 组合完整路径
            string configFilePath = System.IO.Path.Combine(userHome, configFileName);

            if (File.Exists(configFilePath))
            {
                var content = File.ReadAllText(configFilePath);
                if (null != content && content.Length > 0 && content.StartsWith("{") && content.EndsWith("}"))
                {
                    SvnAuthenticationInfo svnAuthenticationInfo = JsonSerializer.Deserialize<SvnAuthenticationInfo>(content)!;
                    SvnUserName = svnAuthenticationInfo.Username!;
                }
            }
        }

        [RelayCommand]
        private void LoadTableConfiguration()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Multiselect = false;
            openFileDialog.Title = "请选择表说明文件";
            openFileDialog.Filter = "Excel文件 (*.xls, *.xlsx)|*.xls;*.xlsx|Excel 97-2003工作簿 (*.xls)|*.xls|Excel工作簿 (*.xlsx)|*.xlsx";
            openFileDialog.CheckFileExists = true;
            if (openFileDialog.ShowDialog() == true)
            {
                ExcelFilePath = openFileDialog.FileName;

                // 判断是否存在版本控制
                using (SvnClient client = new SvnClient())
                {
                    try
                    {
                        // 配置参数，禁止抛出异常
                        SvnInfoArgs args = new SvnInfoArgs { ThrowOnError = false };
                        Collection<SvnInfoEventArgs> info;
                        // 尝试获取信息
                        HasVersionControl = client.GetInfo(SvnTarget.FromString(ExcelFilePath), args, out info);
                    }
                    catch (SvnException) // 捕获 SharpSvn 可能抛出的异常
                    {
                        HasVersionControl = false;
                    }
                    catch (Exception ignored) // 捕获其他可能异常（如路径不存在）
                    {
                        Environment.Exit(0);
                    }
                }

                // 读取Excel内容
                using (FileStream fileStream = new FileStream(ExcelFilePath, FileMode.Open, FileAccess.Read))
                {
                    IWorkbook workbook = WorkbookFactory.Create(fileStream);
                    for (int sheetIndex = 0; sheetIndex < workbook.NumberOfSheets; sheetIndex++)
                    {
                        ISheet sheet = workbook.GetSheetAt(sheetIndex);
                        Console.WriteLine($"=== 工作表: {sheet.SheetName} ===");

                        // 遍历工作表中的所有行
                        for (int rowIndex = 0; rowIndex <= sheet.LastRowNum; rowIndex++)
                        {
                            IRow row = sheet.GetRow(rowIndex);

                            // 检查行是否为空（例如，某些行可能被跳过或为空）
                            if (row == null)
                            {
                                // Console.WriteLine("(空行)");
                                continue; // 跳过空行
                            }

                            // 5. 遍历行中的所有单元格
                            for (int cellIndex = 0; cellIndex < row.LastCellNum; cellIndex++)
                            {
                                ICell cell = row.GetCell(cellIndex);

                                // 获取单元格的值
                                string cellValue = GetCellValue(cell);
                                Console.Write($"{cellValue}\t");
                            }
                            Console.WriteLine(); // 换行
                        }
                        Console.WriteLine(); // 工作表之间空行
                    }
                }

            }
        }

        /// <summary>
        /// 一个辅助方法，用于安全地获取各种类型单元格的值
        /// </summary>
        /// <param name="cell">单元格对象</param>
        /// <returns>单元格值的字符串表示</returns>
        private static string GetCellValue(ICell cell)
        {
            if (cell == null)
                return "(空)"; // 或 return string.Empty;

            // 根据单元格的类型来获取值
            switch (cell.CellType)
            {
                case CellType.String:
                    return cell.StringCellValue;
                case CellType.Numeric:
                    return cell.NumericCellValue.ToString();
                case CellType.Boolean:
                    return cell.BooleanCellValue.ToString();
                case CellType.Blank:
                    return string.Empty; // 或 "(空)";
                case CellType.Error:
                    return FormulaError.ForInt(cell.ErrorCellValue).String; // 获取错误信息
                default:
                    return cell.ToString(); // 通用回退，尝试解析任何类型
            }
        }

        /// <summary>
        /// 关闭窗口时销毁逻辑
        /// </summary>
        public void Dispose()
        {
            _messenger.UnregisterAll(this);
        }
    }
}
